#!python
# SCons based build file for the property template crap
# Base file
import SCons.Environment;   # Get the environment crap
import SCons;
import SConsAddons.Util
import SConsAddons.Options.Pyste
import SConsAddons.Options.Boost
import SConsAddons.Options
import sys;
import os;
import re;
import string;
import wing.wingdbstub;       # stuff for debugging

pj = os.path.join;

# ##################################################
# Helper methods
# ##################################################

GetPlatform = SConsAddons.Util.GetPlatform
Export('GetPlatform')

def BuildLinuxEnvironment():
   "Builds a base environment for other modules to build on set up for linux"
   global optimize, profile, builders

   CXX = os.path.basename(WhereIs('g++3') or 'g++')
   LINK = CXX
   CXXFLAGS = ['-Wall', '-fexceptions']
   LINKFLAGS = []

   # Enable profiling?
   if profile:
      CXXFLAGS.extend(['-pg'])
      LINKFLAGS.extend(['-pg'])

   # Debug or optimize build?
   if optimize:
      CXXFLAGS.extend(['-DNDEBUG', '-O2','-fvisibility=hidden'])
   else:
      CXXFLAGS.extend(['-D_DEBUG', '-g','-fvisibility=hidden'])

   return Environment(
      ENV         = os.environ,
      CXX         = CXX,
      CXXFLAGS    = CXXFLAGS,
      LINK        = LINK,
      LINKFLAGS   = LINKFLAGS
   )

def BuildIRIXEnvironment():
   "Builds a base environment for other modules to build on set up for IRIX"
   global optimize, profile, builders

   CXX = 'CC'
   LINK = CXX
   CXXFLAGS = ['-n32', '-mips3', '-LANG:std', '-w2']
   LINKFLAGS = CXXFLAGS

   # Enable profiling?
   if profile:
      CXXFLAGS.extend([])
      LINKFLAGS.extend([])

   # Debug or optimize build?
   if optimize:
      CXXFLAGS.extend(['-DNDEBUG', '-O2'])
   else:
      CXXFLAGS.extend(['-D_DEBUG', '-g', '-gslim'])

   return Environment(
      ENV         = os.environ,
      CXX         = CXX,
      CXXFLAGS    = CXXFLAGS,
      LINK        = LINK,
      LINKFLAGS   = LINKFLAGS
   )

def BuildWin32Environment():
   return Environment(ENV = os.environ)
                 
# ###############################
# Create builder
# ###############################
help_text = "\n---- The Build System ----\n";

# Get command-line arguments
optimize = ARGUMENTS.get('optimize', 'no').lower() == 'yes'
profile = ARGUMENTS.get('profile', 'no').lower() == 'yes'
   
# Create and export the base environment
if GetPlatform() == 'irix':
   env = BuildIRIXEnvironment()
elif GetPlatform() == 'linux':
   env = BuildLinuxEnvironment()
elif GetPlatform() == 'win32':
   env = BuildWin32Environment()
else:
   print 'Unsupported build environment: ' + GetPlatform()
   sys.exit(-1)

# --- Add options --- #
opts = SConsAddons.Options.Options(files = ['options.cache', 'options.custom'], args = ARGUMENTS);
boost_options = SConsAddons.Options.Boost.Boost("boost","1.31.0",
                                                useDebug=not optimize,
                                                useMt = True,
                                                libs = ['python',],
                                                required=True, useCppPath=True)
pyste_opt = SConsAddons.Options.Pyste.Pyste("pyste","0.9.26", required=True)

opts.AddOption( pyste_opt)
opts.AddOption( boost_options )

help_text += opts.GenerateHelpText(env);
help_text += """
You can store configuration options in the file: options.custom
This file will be loaded each time.  Note: Options are cached in the file: options.cache.
"""

if not SConsAddons.Util.hasHelpFlag():
   print "Setting up build settings...\n";
   opts.Update(env);
   opts.Save('options.cache', env);

   # Add environment
   boost_options.updateEnv(env)      
   pyste_opt.updateEnv(env)                     # Add on the pyste options

   # Add dynamic linking library
   if GetPlatform() != 'win32':
      env.Append(LIBS = ['dl',])

   hello_mod = env.PysteBuilder('hello_module.cpp', 'hello.pyste');
   print "Hello mod: ", hello_mod

   # --- Set up sources --- #
   hello_app_srcs = [];  # List of source files for the app
   hello_app_srcs += Split(""" hello_main.cpp """);
   hello_module_srcs = [hello_mod,];
   #hello_module_srcs += Split(""" Hello_module.cpp """);

   env.Append(CPPPATH = Dir("."));  # Append my directory to the search path
   
   # Other build options
   prog_env = env.Copy()
   boost_options.updatePythonEmbeddedEnv(prog_env)
   print "prog env:", prog_env['LIBS']
   print "hello_app_srcs srcs: ", [str(f) for f in hello_app_srcs];
   prog_env.Program('helloapp', hello_app_srcs);
   prog_env.Program('bp_test', ['bp_test_main.cpp'])
   
   pymod_env = env.Copy();
   boost_options.updatePythonModEnv(pymod_env)
   pymod_env.SharedLibrary('hello', hello_module_srcs);
   
   #env.Install(dir='/var/tmp',source='#/test/data/zero_base_elements.xml');

Default(".");

# ---- List targets ----- #
#help_text += """
#Targets:
#   - tests: Build the test suite (and if I was smarter it would run)
#   - runtests: If I was really smart this would run then after building
#"""

Help(help_text);

# end
